package com.intellagric.service.sso.impl.module;

import com.intellagric.common.jedis.JedisClient;
import com.intellagric.common.pojo.ResponseMessage;
import com.intellagric.common.utils.CookieUtils;
import com.intellagric.common.utils.JsonUtils;
import com.intellagric.mapper.*;
import com.intellagric.pojo.*;
import com.intellagric.service.sso.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Auther: zhy
 * @Date: 2018/10/6
 * @Description: 用户登录接口实现类
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private JedisClient jedisClient;

    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;

    @Override
    public ResponseMessage login(String username, String password) {
        //判断登录数据是否正确
        SysUserExample userExample = new SysUserExample();
        userExample.createCriteria().andLoginNameEqualTo(username);
        List<SysUser> sysUsers = sysUserMapper.selectByExample(userExample);
        if (sysUsers.size() == 0 || sysUsers == null) {
            return ResponseMessage.fail("用户名或者密码错误");
        }
        SysUser user = sysUsers.get(0);
        if (!user.getPassword().equals(password)) {
            return ResponseMessage.fail("用户名或者密码错误");
        }

        SysUserRoleExample sysUserRoleExample = new SysUserRoleExample();
        sysUserRoleExample.createCriteria().andUserIdEqualTo(user.getId());
        List<SysUserRoleKey> sysUserRoleKeys = sysUserRoleMapper.selectByExample(sysUserRoleExample);
        if (sysUserRoleKeys.size() != 0) {
            //查询角色的权限信息
            String roleId = sysUserRoleKeys.get(0).getRoleId();
            user.setRoleId(roleId);
        }
        //查询用户角色，然后查询角色对应权限
        /*
        if (sysUserRoleKeys.size() != 0) {
            //查询角色的权限信息
            SysRoleMenuExample sysRoleMenuExample = new SysRoleMenuExample();
            sysRoleMenuExample.createCriteria().andRoleIdEqualTo(sysUserRoleKeys.get(0).getRoleId());
            List<SysRoleMenuKey> menuKeys = sysRoleMenuMapper.selectByExample(sysRoleMenuExample);
            String[] menuIds = new String[menuKeys.size()];
            for (int i = 0;i < menuKeys.size();i++) {
                menuIds[i] = menuKeys.get(i).getMenuId();
            }
            List<SysMenu> permissionList = getPermissionByRole(menuIds);
            user.setPermissionList(permissionList);//设置用户权限集合
        }*/

        //如果正确则生成token，获取用户信息，保存到session中（redis缓存，模拟session）
        //写入格式：key：token value：用户信息
        String token = UUID.randomUUID().toString();
        user.setPassword(null);
        jedisClient.set("SESSION:" + token, JsonUtils.objectToJson(user));
        //设置session过期时间，配置文件中配置
        jedisClient.expire("SESSION:" + token,SESSION_EXPIRE);
        return ResponseMessage.success("登录成功").add("token",token);
    }

    /**
     * 通过角色id查询菜单列表信息,并生成菜单树
     * @return LayuiDataGridResult
     */
    private List<SysMenu> getPermissionByRole(String[] menuIds){
        //获取所有的角色的权限列表
        List<SysMenu> menuList = new ArrayList<>();
        for (String menuId:menuIds) {
            menuList.add(sysMenuMapper.selectByPrimaryKey(menuId));
        }
        Collections.sort(menuList, new Comparator<SysMenu>() {
            @Override
            public int compare(SysMenu o1, SysMenu o2) {
                return o1.getSort() > o2.getSort() ? 1 : -1;//升序排列
            }
        });

        //查询其中的顶级分类
        List<SysMenu> rootMenuList = new ArrayList<>();
        for (SysMenu menu: menuList) {
            if (menu.getParentId().equals("0")) {
                rootMenuList.add(menu);
            }
        }

        //生成树形菜单数据，为一级菜单设置子菜单，getChild是递归调用的
        for (SysMenu menu : rootMenuList) {
            menu.setChildren(getChild(menu.getId(), menuList));
        }

        return rootMenuList;
    }

    private List<SysMenu> getChild(String id,List<SysMenu> menuList) {
        // 子菜单
        List<SysMenu> childList = new ArrayList<>();

        // 遍历所有节点，将父菜单id与传过来的id比较
        for (SysMenu Menu : menuList) {
            if (Menu.getParentId() != null) {   //所有非以及菜单的都要加入chidList中（递归）
                if (Menu.getParentId().equals(id)) {
                    childList.add(Menu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (SysMenu Menu : childList) {// 没有url子菜单还有子菜单（暂不考虑url的问题）
            // 递归
            Menu.setChildren(getChild(Menu.getId(), menuList));
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}
